﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.IO;

namespace GGEditor.API.Utility.Forms
{
    public partial class ExceptionForm : Form
    {
        private Exception exception;

        public ExceptionForm()
        {
            InitializeComponent();
            raisedTime = DateTime.Now;
        }

        private string productName;

        public Exception Exception
        {
            get { return exception; }
            set { exception = value; }
        }

        public string ProductName
        {
            get { return productName; }
            set
            {
                productName = value;
                Text = Title;
            }
        }

        public string Title
        {
            get
            {
                return string.IsNullOrEmpty(ProductName) ? "" : ProductName + " - " + title;
            }
            set
            {
                title = value;
                Text = Title;
            }
        }

        private readonly DateTime raisedTime;

        private void ExceptionForm_Shown(object sender, EventArgs e)
        {
            if (exception == null)
                return;
            exceptionReport.Text = new ExceptionFormatter(exception).ToString();
        }

        private string title;

        private void saveButton_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.OverwritePrompt = true;
            sfd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            sfd.FileName = string.Format("{0}Error Report {1}.txt",
                string.IsNullOrEmpty(ProductName) ? "" : ProductName + " ",
                raisedTime.ToString("yyyyMMddHHmm"));
            if (sfd.ShowDialog() == DialogResult.Cancel)
                return;
            try {
                using (TextWriter w = new StreamWriter(sfd.FileName))
                    w.Write(exceptionReport.Text);
            } catch {}
        }

        private void debugButton_Click(object sender, EventArgs e)
        {
            throw new ApplicationException("Exception debugging mode.", exception);
        }

        private void quitButton_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
    }
}
